﻿using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.ClayObject;
using SHZY.Common.Configuration;
using SHZY.Common.Models.NPOI;
using SHZY.DataEncryption;
using SHZY.Common.Enum;
using SHZY.Common.Extension;
using SHZY.Common.Filter;
using SHZY.Common.Models;
using SHZY.Common.Security;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Entitys.Permission;
using SHZY.Systems.Entitys.System;
using SHZY.BaseData.Entitys.Dto.QmsBaseInnspectiondefault;
using SHZY.BaseData.Entitys;
using SHZY.BaseData.Interfaces;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using SHZY.Common.Core.Manager.Files;
using Microsoft.AspNetCore.Http;
using SHZY.Common.Helper;
using SHZY.Systems.Interfaces.System;
using Senparc.Weixin.Work.AdvancedAPIs.OaDataOpen;

namespace SHZY.BaseData;

/// <summary>
/// 业务实现：检验项目默认值.
/// </summary>
[ApiDescriptionSettings(Tag = "BaseData", Name = "Innspectiondefault", Order = 200)]
[Route("api/BaseData/[controller]")]
public class QmsBaseInnspectiondefaultService : IQmsBaseInnspectiondefaultService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<QmsBaseInnspectiondefaultEntity> _repository;

    /// <summary>
    /// 多租户事务.
    /// </summary>
    private readonly ITenant _db;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 文件管理.
    /// </summary>
    private readonly IFileManager _fileManager;
    /// <summary>
    /// 检验项目服务.
    /// </summary>
    private readonly IQmsBaseInnspectionitemsService _innspectionitemsService;
    /// <summary>
    /// 检验条目服务.
    /// </summary>
    private readonly IQmsBaseInnspectionentryService _innspectionentryService;
    /// <summary>
    /// 检验方法服务.
    /// </summary>
    private readonly IQmsBaseInnspectionmethodService _innspectionmethod;

    /// <summary>
    /// 初始化一个<see cref="QmsBaseInnspectiondefaultService"/>类型的新实例.
    /// </summary>
    public QmsBaseInnspectiondefaultService(
        ISqlSugarRepository<QmsBaseInnspectiondefaultEntity> qmsBaseInnspectiondefaultRepository,
        ISqlSugarClient context,
        IFileManager fileManager,
        IUserManager userManager,
        IQmsBaseInnspectionitemsService innspectionitemsService,
        IQmsBaseInnspectionentryService innspectionentryService,
        IQmsBaseInnspectionmethodService innspectionmethod
        )
    {
        _repository = qmsBaseInnspectiondefaultRepository;
        _db = context.AsTenant();
        _fileManager = fileManager;
        _userManager = userManager;
        _innspectionitemsService = innspectionitemsService;
        _innspectionentryService = innspectionentryService;
        _innspectionmethod = innspectionmethod;
    }

    /// <summary>
    /// 获取检验项目默认值.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<QmsBaseInnspectiondefaultInfoOutput>();
    }

    /// <summary>
    /// 获取检验项目默认值，根据检验项目与检验条目查询
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("GetInfo")]
    public async Task<dynamic> GetInfo([FromQuery] QmsBaseInnspectiondefaultListQueryInput input)
    {
        return (await _repository.FirstOrDefaultAsync(x => x.InnspectionName == input.innspectionName && x.EntryName == input.entryName && x.DeleteMark == null && x.EnabledMark == 1)).Adapt<QmsBaseInnspectiondefaultInfoOutput>();
    }

    /// <summary>
    /// 获取所有检验项目默认值.
    /// </summary>
    /// <returns></returns>
    [HttpGet("All")]
    public async Task<dynamic> GetListAll()
    {
        var data = await _repository.AsQueryable().Where(x => x.DeleteMark == null && x.EnabledMark == 1)
            .OrderBy(x => x.CreatorTime).ToListAsync();
        return new { list = data.Adapt<List<QmsBaseInnspectiondefaultInfoOutput>>() };

    }

    /// <summary>
    /// 获取检验项目默认值列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] QmsBaseInnspectiondefaultListQueryInput input)
    {
        var queryable = _repository.Context.Queryable<QmsBaseInnspectiondefaultEntity,
            QmsBaseInnspectionitemsEntity, QmsBaseInnspectionentryEntity, QmsBaseInnspectionmethodEntity>((a, b, c, d) => new JoinQueryInfos(JoinType.Left, a.InnspectionName == b.Id, JoinType.Left, a.EntryName == c.Id, JoinType.Left, a.Method == d.Id))
            .WhereIF(!string.IsNullOrEmpty(input.innspectionName), a => a.InnspectionName.Equals(input.innspectionName))
            .WhereIF(!string.IsNullOrEmpty(input.entryName), a => a.EntryName.Equals(input.entryName))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), a => a.InnspectionName.Contains(input.keyword) || a.EntryName.Contains(input.keyword))
            .Where(a => a.DeleteMark == null)
            .Select((a, b, c, d) => new QmsBaseInnspectiondefaultListOutput
            {
                id = a.Id,
                innspectionName = b.InnspectionName,
                entryName = c.InnspectionName,
                method = d.Name,
                unit = a.Unit,
                accuracy = a.Accuracy.ToString(),
                type = SqlFunc.IIF(a.Type == "ration", "定量", "定性"),
                enabledMark = SqlFunc.IIF(a.EnabledMark == 0, "停用", "正常"),
            }).MergeTable();
        if (!string.IsNullOrEmpty(input.sidx))
        {
            queryable.OrderBy(input.sidx + " " + input.sort);
        }
        else
        {
            queryable.OrderBy(it => it.id);
        }
        var data = await queryable.ToPagedListAsync(input.currentPage, input.pageSize);
        return PageResult<QmsBaseInnspectiondefaultListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 新建检验项目默认值.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] QmsBaseInnspectiondefaultCrInput input)
    {
        if (await _repository.AnyAsync(x => (x.InnspectionName == input.innspectionName && x.EntryName == input.entryName) && x.DeleteMark == null))
            throw Oops.Oh("所选检验项目与检验条目已维护默认值");
        var entity = input.Adapt<QmsBaseInnspectiondefaultEntity>();
        var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
        if (isOk < 1)
            throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 获取检验项目默认值无分页列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    private async Task<dynamic> GetNoPagingList([FromQuery] QmsBaseInnspectiondefaultListQueryInput input)
    {
        var queryable = _repository.Context.Queryable<QmsBaseInnspectiondefaultEntity,
            QmsBaseInnspectionitemsEntity, QmsBaseInnspectionentryEntity, QmsBaseInnspectionmethodEntity>((a, b, c, d) => new JoinQueryInfos(JoinType.Left, a.InnspectionName == b.Id, JoinType.Left, a.EntryName == c.Id, JoinType.Left, a.Method == d.Id))
            .WhereIF(!string.IsNullOrEmpty(input.innspectionName), a => a.InnspectionName.Equals(input.innspectionName))
            .WhereIF(!string.IsNullOrEmpty(input.entryName), a => a.EntryName.Equals(input.entryName))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), a => a.InnspectionName.Contains(input.keyword) || a.EntryName.Contains(input.keyword))
            .Where(a => a.DeleteMark == null)
            .OrderByIF(string.IsNullOrEmpty(input.sidx), a => a.Id);
        if (!string.IsNullOrEmpty(input.sidx))
        {
            queryable.OrderBy(input.sidx + " " + input.sort);
        }
        var data = await queryable.Select((a, b, c, d) => new QmsBaseInnspectiondefaultListOutput
        {
            id = a.Id,
            innspectionName = b.InnspectionName,
            entryName = c.InnspectionName,
            method = d.Name,
            unit = a.Unit,
            accuracy = a.Accuracy.ToString(),
            type = SqlFunc.IIF(a.Type == "ration", "定量", "定性"),
            enabledMark = SqlFunc.IIF(a.EnabledMark == 0, "停用", "正常"),
        }).ToListAsync();

        return data;
    }

    /// <summary>
    /// 导出检验项目默认值.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("Actions/Export")]
    public async Task<dynamic> Export([FromQuery] QmsBaseInnspectiondefaultListQueryInput input)
    {
        var exportData = new List<QmsBaseInnspectiondefaultListOutput>();
        if (input.dataType == 0)
            exportData = Clay.Object(await GetList(input)).Solidify<PageResult<QmsBaseInnspectiondefaultListOutput>>().list;
        else
            exportData = await GetNoPagingList(input);
        List<ParamsModel> paramList = "[{\"value\":\"检验项目\",\"field\":\"innspectionName\"},{\"value\":\"检验条目\",\"field\":\"entryName\"},{\"value\":\"类型\",\"field\":\"type\"},{\"value\":\"检验⽅法\",\"field\":\"method\"},{\"value\":\"单位\",\"field\":\"unit\"},{\"value\":\"精度\",\"field\":\"accuracy\"},{\"value\":\"有效标志\",\"field\":\"enabledMark\"},]".ToList<ParamsModel>();
        ExcelConfig excelconfig = new ExcelConfig();
        excelconfig.FileName = "检验项目默认值.xls";
        excelconfig.HeadFont = "微软雅黑";
        excelconfig.HeadPoint = 10;
        excelconfig.IsAllSizeColumn = true;
        excelconfig.ColumnModel = new List<ExcelColumnModel>();
        foreach (var item in input.selectKey.Split(',').ToList())
        {
            var isExist = paramList.Find(p => p.field == item);
            if (isExist != null)
                excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
        }

        var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
        ExcelExportHelper<QmsBaseInnspectiondefaultListOutput>.Export(exportData, excelconfig, addPath);
        var fileName = _userManager.UserId + "|" + addPath + "|xls";
        return new
        {
            name = excelconfig.FileName,
            url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "SHZY")
        };
    }

    /// <summary>
    /// 批量删除检验项目默认值.
    /// </summary>
    /// <param name="ids">主键数组.</param>
    /// <returns></returns>
    [HttpPost("batchRemove")]
    public async Task BatchRemove([FromBody] List<string> ids)
    {
        var entitys = await _repository.Context.Queryable<QmsBaseInnspectiondefaultEntity>().In(it => it.Id, ids).ToListAsync();
        if (entitys.Count > 0)
        {
            try
            {
                // 开启事务
                _db.BeginTran();

                // 批量删除客户信息
                var isOk = await _repository.Context.Updateable<QmsBaseInnspectiondefaultEntity>().SetColumns(it => new QmsBaseInnspectiondefaultEntity()
                {
                    DeleteTime = DateTime.Now,
                    DeleteMark = 1,
                    DeleteUserId = _userManager.UserId
                }).Where(it => ids.Contains(it.Id)).ExecuteCommandHasChangeAsync();

                // 关闭事务
                _db.CommitTran();
            }
            catch (Exception)
            {
                // 回滚事务
                _db.RollbackTran();

                throw Oops.Oh(ErrorCode.COM1002);
            }
        }
    }

    /// <summary>
    /// 更新检验项目默认值.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] QmsBaseInnspectiondefaultUpInput input)
    {
        if (await _repository.AnyAsync(x => (x.InnspectionName == input.innspectionName && x.EntryName == input.entryName) && x.DeleteMark == null && x.Id != input.id))
            throw Oops.Oh("所选检验项目与检验条目已维护默认值");
        var entity = input.Adapt<QmsBaseInnspectiondefaultEntity>();
        var isOk = await _repository.Context.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).CallEntityMethod(m => m.LastModify()).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1001);
    }

    /// <summary>
    /// 删除检验项目默认值.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Updateable<QmsBaseInnspectiondefaultEntity>().SetColumns(it => new QmsBaseInnspectiondefaultEntity()
        {
            DeleteTime = DateTime.Now,
            DeleteMark = 1,
            DeleteUserId = _userManager.UserId
        }).Where(x => x.Id == id).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1002);
    }


    /// <summary>
    /// 上传文件.
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [HttpPost("Uploader")]
    public async Task<dynamic> Uploader(IFormFile file)
    {
        try
        {
            var _filePath = _fileManager.GetPathByType(string.Empty);
            var _fileName = DateTime.Now.ToString("yyyyMMdd") + "_" + SnowflakeIdHelper.NextId() + Path.GetExtension(file.FileName);
            var stream = file.OpenReadStream();
            await _fileManager.UploadFileByType(stream, _filePath, _fileName);
            return new { name = _fileName, url = string.Format("/api/File/Image/{0}/{1}", string.Empty, _fileName) };

        }
        catch (Exception ex)
        {
            throw Oops.Oh(ErrorCode.D8001);
        }
    }

    /// <summary>
    /// 导入数据.
    /// </summary>
    /// <param name="input">请求参数</param>
    /// <returns></returns>
    [HttpPost("ImportData")]
    public async Task<dynamic> ImportData([FromBody] QmsBaseInnspectiondefaultImportDataInput input)
    {
        var output = new QmsBaseInnspectiondefaultImportDataOutput();
        var qmsBaseInnspectionitemsList = await _repository.Context.Queryable<QmsBaseInnspectionitemsEntity>().Where(x => x.DeleteMark == null && x.EnabledMark == 1).OrderBy(x => x.InnspectionName).ToListAsync();
        var qmsBaseInnspectionentryList = await _repository.Context.Queryable<QmsBaseInnspectionentryEntity>().Where(x => x.DeleteMark == null && x.EnabledMark == 1).OrderBy(x => x.InnspectionName).ToListAsync();
        var qmsBaseInnspectionmethodsList = await _repository.Context.Queryable<QmsBaseInnspectionmethodEntity>().Where(x => x.DeleteMark == null && x.EnabledMark == 1).OrderBy(x => x.Name).ToListAsync();
        foreach (var item in input.list)
        {
            try
            {
                if (string.IsNullOrEmpty(item.innspectionName))
                {
                    item.exceptionMsg = "检验项目不能为空！";
                    output.failResult.Add(item);
                    output.fnum++;
                    continue;
                }
                if (string.IsNullOrEmpty(item.entryName))
                {
                    item.exceptionMsg = "检验条目不能为空！";
                    output.failResult.Add(item);
                    output.fnum++;
                    continue;
                }
                if (string.IsNullOrEmpty(item.type))
                {
                    item.exceptionMsg = "类型不能为空！";
                    output.failResult.Add(item);
                    output.fnum++;
                    continue;
                }
                else
                {
                    if (item.type != "定量" && item.type != "定性")
                    {
                        item.exceptionMsg = "请选择类型！";
                        output.failResult.Add(item);
                        output.fnum++;
                        continue;
                    }
                    if (item.type == "定量")
                    {
                        item.type = "ration";
                    }
                    if (item.type == "定性")
                    {
                        item.type = "qualitative";
                    }
                }
                if (string.IsNullOrEmpty(item.method))
                {
                    item.exceptionMsg = "检验⽅法不能为空！";
                    output.failResult.Add(item);
                    output.fnum++;
                    continue;
                }
                if (!string.IsNullOrEmpty(item.unit) && item.unit?.Length > 20)
                {
                    item.exceptionMsg = "检验⽅单位超出指定长度！";
                    output.failResult.Add(item);
                    output.fnum++;
                    continue;
                }
                var qmsBaseInnspectionitemsEntity = qmsBaseInnspectionitemsList.Find(x => x.InnspectionName.Equals(item.innspectionName));
                if (qmsBaseInnspectionitemsEntity == null)
                {
                    item.exceptionMsg = "检验项目无法识别！";
                    output.failResult.Add(item);
                    output.fnum++;
                    continue;
                }
                var qmsBaseInnspectionentryEntity = qmsBaseInnspectionentryList.Find(x => x.InnspectionName.Equals(item.entryName) && x.ItemsId == qmsBaseInnspectionitemsEntity.Id);
                if (qmsBaseInnspectionentryEntity == null)
                {
                    item.exceptionMsg = "检验条目无法识别！";
                    output.failResult.Add(item);
                    output.fnum++;
                    continue;
                }
                var qmsBaseInnspectionmethodEntity = qmsBaseInnspectionmethodsList.Find(x => x.Name.Equals(item.method));
                if (qmsBaseInnspectionmethodEntity == null)
                {
                    item.exceptionMsg = "检验⽅法无法识别！";
                    output.failResult.Add(item);
                    output.fnum++;
                    continue;
                }
                if (await _repository.AnyAsync(x => x.InnspectionName == qmsBaseInnspectionitemsEntity.Id && x.EntryName == qmsBaseInnspectionentryEntity.Id && x.DeleteMark == null))
                {
                    item.exceptionMsg = "检验项目与检验条目已维护默认值！";
                    output.failResult.Add(item);
                    output.fnum++;
                    continue;
                }
                if (item.accuracy != null)
                {
                    int num = 0;
                    System.Text.RegularExpressions.Regex regex = new
                    System.Text.RegularExpressions.Regex(@"^[0-9]\d*$");
                    if (regex.IsMatch(item.accuracy))
                    {
                        item.exceptionMsg = "精度不可输入小数！";
                        output.failResult.Add(item);
                        output.fnum++;
                        continue;
                    }

                    if (Convert.ToInt32(item.accuracy) < 0 || Convert.ToInt32(item.accuracy) > 6)
                    {
                        item.exceptionMsg = "精度不可小于0或大于6！";
                        output.failResult.Add(item);
                        output.fnum++;
                        continue;
                    }
                }
                var entity = item.Adapt<QmsBaseInnspectiondefaultEntity>();
                entity.InnspectionName = qmsBaseInnspectionitemsEntity.Id;
                entity.EntryName = qmsBaseInnspectionentryEntity.Id;
                entity.Method = qmsBaseInnspectionmethodEntity.Id;
                entity.Accuracy = item.accuracy == null ? 0 :  Convert.ToInt32(item.accuracy);

                var isOK = await _repository.Context.Insertable(entity).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                if (isOK < 1)
                {
                    output.failResult.Add(item);
                    output.fnum++;
                }
                else
                {
                    output.snum++;
                }
            }
            catch (Exception ex)
            {
                item.exceptionMsg = ex.Message;
                output.failResult.Add(item);
                output.fnum++;
            }
        }
        if (output.snum == input.list.Count)
        {
            output.resultType = 1;
        }
        else
        {
            output.resultType = 0;
        }
        return output;
    }

    /// <summary>
    /// 模板下载.
    /// </summary>
    /// <returns></returns>
    [HttpGet("TemplateDownload")]
    public async Task<dynamic> TemplateDownload()
    {
        string _fileName = "检验项目默认值模板.xlsx";
        var filePath = Path.Combine(FileVariable.TemplateFilePath, "Innspectiondefault_import_template.xlsx"); // 模板路径
        var addFilePath = Path.Combine(FileVariable.TemplateFilePath, _fileName); // 保存路径
        if (!(await _fileManager.ExistsFile(addFilePath)))
        {
            var stream = await _fileManager.GetFileStream(filePath);
            await _fileManager.UploadFileByType(stream, FileVariable.TemporaryFilePath, _fileName);
        }

        return new { name = _fileName, url = "/api/file/Download?encryption=" + DESCEncryption.Encrypt(_userManager.UserId + "|" + _fileName, "SHZY") };
    }

    /// <summary>
    /// 导入预览.
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    [HttpGet("ImportPreview")]
    public async Task<dynamic> ImportPreview(string fileName)
    {
        try
        {
            var filePath = FileVariable.TemporaryFilePath;
            var savePath = Path.Combine(filePath, fileName);
            // 得到数据
            var sr = await _fileManager.GetFileStream(savePath);
            var excelData = ExcelImportHelper.ToDataTable(savePath, sr);
            foreach (var item in excelData.Columns)
            {
                excelData.Columns[item.ToString()].ColumnName = GetFileEncode(item.ToString());
            }
            // 删除文件
            await _fileManager.DeleteFile(savePath);
            // 返回结果
            return new { dataRow = excelData };
        }
        catch (Exception)
        {

            throw Oops.Oh(ErrorCode.D1801);
        }
    }
    /// <summary>
    /// 获取字段编码.
    /// </summary>
    /// <param name="filed"></param>
    /// <returns></returns>
    private string GetFileEncode(string filed)
    {
        switch (filed)
        {
            case "检验项目":
                return "innspectionName";
            case "检验条目":
                return "entryName";
            case "类型":
                return "type";
            case "单位":
                return "unit";
            case "检验⽅法":
                return "method";
            case "精度":
                return "accuracy";
            default:
                return string.Empty;
        }

    }
}